package com.koudai.finance.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.koudai.finance.constant.WebConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;

/**
 * @Description: 阿里云oss工具类
 * @author: ls
 * @Date: 2020/7/14 10:45
 */
@Slf4j
@Component
public class OssUtils {

    private OSS instance;

    @Resource
    private WebConfig webConfig;

    @PostConstruct
    public void initialize() {
        instance = new OSSClientBuilder().build(webConfig.getOssEndPoint(), webConfig.getOssAccessKey(), webConfig.getOssAccessKeySecret());
    }

    /**
     * @Description: 上传文件
     * @author: ls
     * @Date: 2020/7/14 10:46
     */
    public void uploadFile(File file, String key) {
        OSS instance = new OSSClientBuilder().build("oss-cn-beijing.aliyuncs.com", "LTAI4G8ct17ymvoo91fyPVoZ", "LKMSaIEvyFVFOg2vz5oCKtI5xNXJs6");
        instance.putObject("test-finance-bucket", key, file);
    }

    /**
     * @Description: 上传文件流
     * @author: ls
     * @Date: 2020/7/14 10:46
     */
    public void uploadFile(InputStream is, String key) {
        instance.putObject(webConfig.getOssBucket(), key, is);
    }

    /**
     * @Description: 下载文件
     * @author: ls
     * @Date: 2020/7/14 10:46
     */
    public void downloadFile(String key, String filename) throws OSSException, ClientException {
        instance.getObject(new GetObjectRequest(webConfig.getOssBucket(), key), new File(filename));
    }

    /**
     * @Description: 删除
     * @author: ls
     * @Date: 2020/7/14 10:46
     */
    public void deleteFile(String key) throws OSSException, ClientException {
        instance.deleteObject(webConfig.getOssBucket(), key);
    }

    /**
     * @Description: 获取文件类型
     * @author: ls
     * @Date: 2020/7/14 10:46
     */
    public String getContentType(String fileName) {
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        return ".bmp".equalsIgnoreCase(fileExtension) ? "image/bmp" : (".gif".equalsIgnoreCase(fileExtension) ? "image/gif" : (!".jpeg".equalsIgnoreCase(fileExtension) && !".jpg".equalsIgnoreCase(fileExtension) && !".png".equalsIgnoreCase(fileExtension) ? (".html".equalsIgnoreCase(fileExtension) ? "text/html" : (".txt".equalsIgnoreCase(fileExtension) ? "text/plain" : (".vsd".equalsIgnoreCase(fileExtension) ? "application/vnd.visio" : (!".ppt".equalsIgnoreCase(fileExtension) && !".pptx".equalsIgnoreCase(fileExtension) ? (!".doc".equalsIgnoreCase(fileExtension) && !".docx".equalsIgnoreCase(fileExtension) ? (".xml".equalsIgnoreCase(fileExtension) ? "text/xml" : (".apk".equalsIgnoreCase(fileExtension) ? "application/vnd.android.package-archive" : (".exe".equalsIgnoreCase(fileExtension) ? "application/octet-stream" : (".rar".equalsIgnoreCase(fileExtension) ? "application/x-rar-compressed" : (".zip".equalsIgnoreCase(fileExtension) ? "application/zip" : (".pdf".equalsIgnoreCase(fileExtension) ? "application/pdf" : (".png".equalsIgnoreCase(fileExtension) ? "application/x-png" : "text/html"))))))) : "application/msword") : "application/vnd.ms-powerpoint")))) : "image/jpeg"));
    }

    /**
     * @Description: 获取oss临时授权的sts信息
     * @Author: ls
     * @Date: 2020/07/28 18:18
     */
    public JSONObject getOssStsInfo() {
        JSONObject jsonObject = new JSONObject();
        String endpoint = "sts.cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI4G5UvHDGd11KN2X54Ryj";
        String accessKeySecret = "EIUy6B4WFtvG8bgJU8IUjRzzRTJI2s";
        String roleArn = "acs:ram::1168439742693949:role/aliyunosstokengeneratorrole";
        String roleSessionName = "lianshuai123";
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:*\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        try {
            DefaultProfile.addEndpoint("", "", "Sts", endpoint);
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            request.setDurationSeconds(1800L);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            jsonObject.put("expiration", response.getCredentials().getExpiration());
            jsonObject.put("accessKeyId", response.getCredentials().getAccessKeyId());
            jsonObject.put("accessKeySecret", response.getCredentials().getAccessKeySecret());
            jsonObject.put("securityToken", response.getCredentials().getSecurityToken());
            jsonObject.put("requestId", response.getRequestId());
            jsonObject.put("bucket", webConfig.getOssBucket());
            return jsonObject;
        } catch (Exception e) {
            log.error("获取oss临时授权的sts信息失败", e);
        }
        return null;
    }

    public static void main(String[] args) {
        new OssUtils().uploadFile(new File("C:\\Users\\Administrator\\Desktop\\压缩海报\\shareposter2.png"), "shareposter2.png")
        ;
    }
}